package com.concurrent.coline.part2.syn;

/**
 * 对象锁
 */
public class ObjectLockSyn {

    /**
     * 使用对象锁的线程
     */
    private static class InstanceSyn implements Runnable{
        private ObjectLockSyn objectLockSyn;

        private InstanceSyn(ObjectLockSyn objectLockSyn) {
            this.objectLockSyn = objectLockSyn;
        }

        @Override
        public void run() {
            System.out.println("TestInstance is running..."+objectLockSyn);
            objectLockSyn.instance();
        }
    }

    /**
     * 使用对象锁的线程
     */
    private static class Instance2Syn implements Runnable{
        private ObjectLockSyn objectLockSyn;

        private Instance2Syn(ObjectLockSyn objectLockSyn) {
            this.objectLockSyn = objectLockSyn;
        }

        @Override
        public void run() {
            System.out.println("TestInstance2 is running..."+objectLockSyn);
            objectLockSyn.instance2();
        }
    }

    //锁对象方式一
    private synchronized void instance() {
        try {
            Thread.sleep(3000);
            System.out.println("objectLockSyn is going..."+this.toString());
            Thread.sleep(3000);
            System.out.println("objectLockSyn ended "+this.toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //锁对象
    private void instance2() {
        synchronized (this){
            try {
                Thread.sleep(3000);
                System.out.println("objectLockSyn2 is going..."+this.toString());
                Thread.sleep(3000);
                System.out.println("objectLockSyn2 ended "+this.toString());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ObjectLockSyn objectLockSyn = new ObjectLockSyn();
        Thread t1 = new Thread(new ObjectLockSyn.InstanceSyn(objectLockSyn));
        Thread t2 = new Thread(new ObjectLockSyn.Instance2Syn(objectLockSyn));

        t1.start();
        t2.start();
    }
}
